package com.yokead.controller.copy;

import cn.jiangzeyin.common.JsonMessage;
import com.yokead.common.Config;
import com.yokead.common.base.AdminBaseControl;
import com.yokead.common.tools.UrlPath;
import com.yokead.system.log.LogType;
import com.yokead.system.log.SystemLog;
import com.yokead.util.EncryptUtil;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.IOException;

/**
 * Created by jiangzeyin on 2017/8/9.
 */
@Controller
@RequestMapping("copy")
public class ReNewsControl extends AdminBaseControl {

    @RequestMapping(value = "renew.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String index(String name) throws IOException {
        setAttribute("data", CopyIndexControl.getInfo(UrlPath.Type.Delete, name, Config.Nginx.getNginxConfigPath()));
        return "copy/renew";
    }

    @RequestMapping(value = "renew.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String get_log(String url, String tag) {
        String path;
        try {
            path = EncryptUtil.decrypt(tag);
            File file = new File(path);
            if (!file.exists()) {
                return JsonMessage.getString(404, "不存在该文案");
            }
            FileCopyUtils.copy(file, new File(file.getParentFile(), "index.html"));
            if (file.delete()) {
                return JsonMessage.getString(200, "");
            }
            return JsonMessage.getString(404, "恢复失败");
        } catch (Exception e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("恢复异常", e);
            return JsonMessage.getString(500, "恢复异常:" + e.getMessage());
        }
    }
}
